package com.lyn.solitude_plugin_host.contentProviders;

import android.app.Service;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lyn.solitude_aidl_host.PluginHostAidlInterface;
import com.lyn.solitude_plugin_host.PluginHost;
import com.lyn.solitude_plugin_host.service.PluginService;

/**
 * @author longyn 2024/05/11
 * @version 1.0.0
 */
public class PluginContentProvider extends ContentProvider {

    private final static String TAG = "PluginContentProvider";
    private PluginHostAidlInterface pluginHostAidlInterface;
    private Context applicationContext;

    @Override
    public boolean onCreate() {
        Log.d(TAG, "onCreate");
        Context context = getContext();
        if (context != null) {
            applicationContext = context.getApplicationContext();
            Intent intent = new Intent(applicationContext, PluginService.class);
            applicationContext.bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
        }
        return true;
    }

    /**
     * 服务连接监听
     */
    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            pluginHostAidlInterface = PluginHostAidlInterface.Stub.asInterface(service);
            Log.d(TAG, "onServiceConnected");
            PluginHost.setPluginHostAidlInterface(pluginHostAidlInterface);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            pluginHostAidlInterface = null;
            Intent intent = new Intent(applicationContext, PluginService.class);
            applicationContext.bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }
}
